package com.kcwl.idea.plugins.base;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;

public class JavadocUtil {
    public static void addJavadoc(PsiField field, String javadocText) {
        PsiElementFactory factory = JavaPsiFacade.getElementFactory(field.getProject());
        PsiElement parent = field.getParent();

        // 创建 Javadoc 注释
        PsiComment javadoc = factory.createCommentFromText("/**\n* " + javadocText + "\n*/", parent);

        // 插入 Javadoc 注释到字段之前
        parent.addBefore(javadoc, field);
    }

    public static void addJavadoc(PsiClass psiClass, String javadocText) {
        PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject());

        // 创建 Javadoc 注释
        PsiComment javadoc = factory.createCommentFromText("/**\n* " + javadocText + "\n*/", psiClass);

        // 插入 Javadoc 注释到字段之前
        psiClass.addBefore(javadoc, psiClass);
    }


    public static void codeFormat(Project project, PsiJavaFile psiFile) {
        PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
        Document document = documentManager.getDocument(psiFile);
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(psiFile.getProject());
        codeStyleManager.reformatText(psiFile, 0, document.getTextLength());
        documentManager.commitDocument(document);

        // 获取代码样式管理器
        JavaCodeStyleManager styleManager = JavaCodeStyleManager.getInstance(project);
        styleManager.optimizeImports(psiFile);
        styleManager.shortenClassReferences(psiFile);
        styleManager.removeRedundantImports(psiFile);
    }
}
